package io.renren.wh.order.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import io.renren.common.utils.RedisUtils;
import io.renren.modules.job.entity.ScheduleJobEntity;
import io.renren.modules.job.service.ScheduleJobService;
import io.renren.modules.job.task.ITask;
import io.renren.modules.job.utils.ScheduleUtils;
import io.renren.wh.common.Constant;
import io.renren.wh.merchant.entity.MerchantKeyEntity;
import io.renren.wh.order.entity.OrderInfoEntity;
import io.renren.wh.order.enums.CallBackStatusEnum;
import io.renren.wh.order.enums.ReCallBackStatusEnum;
import io.renren.wh.order.service.OrderInfoService;
import io.renren.wh.order.util.MySignUtil;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 回调商户任务
 */
@Component("callBackMerchantTask")
public class CallBackMerchantTask implements ITask {

    private String[] cronExpressions = {"0/1 * * * * ?",
            "0/10 * * * * ?",
            "0/15 * * * * ?",
            "0/30 * * * * ?",
            "0/59 * * * * ?"};

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ScheduleJobService scheduleJobService;

    @Autowired
    private Scheduler scheduler;

    /**
     * 只传递订单号
     * @param orderNO   参数，多参数使用JSON数据
     */
    @Override
    public void run(String orderNO) {
        if (!redisTemplate.hasKey(Constant.MERCHANT_KEY+orderNO)){
            return;
        }

        if (!redisTemplate.hasKey(Constant.ORDER_PREFIX+orderNO)){
            return;
        }

        if (!redisTemplate.hasKey(Constant.CALLBACK_PREFIX+orderNO)){
            return;
        }
        ScheduleJobEntity scheduleJob = redisUtils.fromJson(redisUtils.get(Constant.CALLBACK_PREFIX+orderNO),ScheduleJobEntity.class);

        //先暂停，执行完本次任务再视情况恢复
        ScheduleUtils.pauseJob(scheduler,scheduleJob.getJobId());

        MerchantKeyEntity merchantKey = redisUtils.fromJson(redisUtils.get(Constant.MERCHANT_KEY+orderNO),MerchantKeyEntity.class);
        OrderInfoEntity orderInfo = redisUtils.fromJson(redisUtils.get(Constant.ORDER_PREFIX+orderNO),OrderInfoEntity.class);

        Map<String,Object> params = new HashMap<>();
        params.put("orderno",orderInfo.getMerchantordersn()); // 商户订单号
        params.put("amount",orderInfo.getOrderaccount());  //订单金额 单位 分
        params.put("paytype",orderInfo.getInterfacecode()); //订单支付方式
        params.put("sign",MySignUtil.getSign(orderInfo.getMerchantordersn(),orderInfo.getOrderaccount(),orderInfo.getInterfacecode(),merchantKey.getSecretkey()));

        String responseStr = HttpUtil.post(merchantKey.getNotifyUrl(),JSON.toJSONString(params));

        if(responseStr.equals("1")){
            orderInfo.setCallbackstatus(CallBackStatusEnum.YES.type);
            orderInfo.setRecallbackstatus(ReCallBackStatusEnum.AUTO.type);
            orderInfo.setEndtime(new Date());
            //修改订单状态
            orderInfoService.orderCallbackSuccess(orderInfo);
            //删除任务
            scheduleJobService.removeById(scheduleJob.getJobId());
            ScheduleUtils.deleteScheduleJob(scheduler,scheduleJob.getJobId());
            redisUtils.delete(Constant.CALLBACK_PREFIX+orderInfo.getSystemordersn());
        } else {
            //修改任务调用时间
            int i=0;
            //找到当前回调的时间表达式
            for (;i<cronExpressions.length; i++){
                if (scheduleJob.getCronExpression().equals(cronExpressions[i])){
                    break;
                }
            }
            //如果不是最后一个，则继续任务;如果是则
            if (i+1 <= cronExpressions.length-1){
                scheduleJob.setCronExpression(cronExpressions[i+1]);
                //将定时任务存入redis
                redisUtils.set(Constant.CALLBACK_PREFIX+orderInfo.getSystemordersn(),redisUtils.toJson(scheduleJob));
                scheduleJobService.update(scheduleJob);
                //恢复任务
                ScheduleUtils.resumeJob(scheduler,scheduleJob.getJobId());
            } else {
                //删除任务
                scheduleJobService.removeById(scheduleJob.getJobId());
                ScheduleUtils.deleteScheduleJob(scheduler,scheduleJob.getJobId());
                redisUtils.delete(Constant.CALLBACK_PREFIX+orderInfo.getSystemordersn());
            }
        }
    }
}
